package com.love.marriage.cloud.config;

import com.alibaba.fastjson.JSONObject;
import com.alicom.mns.tools.MessageListener;
import com.aliyun.mns.model.Message;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.love.marriage.cloud.service.AliyunDyplsService;
import com.love.marriage.cloud.vo.MessageContent;
import com.love.marriage.common.constants.RedisConstants;
import com.love.marriage.common.enums.DefaultAmountTypeEnum;
import com.love.marriage.common.enums.ResultEnum;
import com.love.marriage.common.enums.TransactionType;
import com.love.marriage.common.exceptions.SystemException;
import com.love.marriage.common.redisKey.VirtualNumberKey;
import com.love.marriage.defaultAmountConfig.service.DefaultAmountConfigService;
import com.love.marriage.defaultAmountConfig.vo.DefaultAmountConfigVo;
import com.love.marriage.userBalanceInfo.service.UserBalanceInfoService;
import com.love.marriage.userBalanceInfo.vo.UserBalanceInfoAddVo;
import com.love.marriage.userChatInfo.service.UserChatInfoService;
import com.love.marriage.userChatInfo.vo.UserChatInfoVo;
import com.love.marriage.userInfo.entity.UserInfo;
import com.love.marriage.userInfo.service.UserInfoService;
import com.love.marriage.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.Duration;

@Slf4j
@Component
@RequiredArgsConstructor
public class MyMessageListener implements MessageListener {

    private final UserInfoService userInfoService;

    private final UserBalanceInfoService userBalanceInfoService;

    private final DefaultAmountConfigService defaultAmountConfigService;

    private final AliyunDyplsService aliyunDyplsService;

    private final RedisUtils redisUtils;

    private final UserChatInfoService userChatInfoService;

    @Override
    public boolean dealMessage(Message message) {
        // 消息的几个关键值
        System.out.println("Thread:" + Thread.currentThread().getName());
        log.info("message handle: " + JSONObject.toJSONString(message));
        MessageContent content = JSONObject.parseObject(message.getMessageBodyAsString(), MessageContent.class);
        if (content == null || content.getStartTime() == null || content.getReleaseTime() == null ||
                content.getStartTime().isEqual(content.getReleaseTime())) {
            return true;
        }
        // 2024/10/27 根据手机号获取当前人信息
        LambdaQueryWrapper<UserInfo> query = Wrappers.<UserInfo>lambdaQuery()
                .eq(UserInfo::getPhone, content.getPhoneNo())
                .eq(UserInfo::getDeleteFlag, 0);
        UserInfo dbUser = userInfoService.getOne(query);
        if (dbUser == null) {
            throw new SystemException(ResultEnum.USER_NOT_EXIST);
        }
        long seconds = Duration.between(content.getStartTime(), content.getReleaseTime()).getSeconds();
        // 代表当前没有通话，直接返回
        if (seconds <= 0) {
            return true;
        }
        redisUtils.delete(VirtualNumberKey.virtualNumberBindingKey.getPrefix()
                + RedisConstants.SEGMENTATION + content.getPhoneNo()
                + RedisConstants.SEGMENTATION + content.getSecretNo()
                + RedisConstants.SEGMENTATION + content.getPeerNo()
                + RedisConstants.SEGMENTATION + content.getSubId());
        // 删除绑定关系
        redisUtils.delete(VirtualNumberKey.virtualNumberBindingSubPhoneKey.getPrefix()
                + RedisConstants.SEGMENTATION + content.getPhoneNo()
                + RedisConstants.SEGMENTATION + content.getSecretNo());
        // 删除绑定关系
        redisUtils.delete(VirtualNumberKey.virtualNumberBindingPhoneKey.getPrefix()
                + RedisConstants.SEGMENTATION + content.getPhoneNo()
                + RedisConstants.SEGMENTATION + content.getPeerNo());
        // 删除a绑定
        redisUtils.delete(VirtualNumberKey.virtualNumberBindingAPhoneKey.getPrefix()
                + RedisConstants.SEGMENTATION + content.getPhoneNo()
                + RedisConstants.SEGMENTATION + content.getSecretNo());
        // 删除b绑定
        redisUtils.delete(VirtualNumberKey.virtualNumberBindingBPhoneKey.getPrefix()
                + RedisConstants.SEGMENTATION + content.getPeerNo()
                + RedisConstants.SEGMENTATION + content.getSecretNo());
        log.info(String.valueOf(seconds));
        int callTime = (int) Math.ceil(seconds / 60.0);
        log.info("dbUserInfo : ========================================:{}", JSONObject.toJSONString(dbUser));
        // 添加默认时间扣减
        UserChatInfoVo userChatInfoVo = userChatInfoService.queryUserChatInfoByUserId(dbUser.getId(), DefaultAmountTypeEnum.CALL_NUM.getCode());
        if (userChatInfoVo != null) {
            if (userChatInfoVo.getChatCount() >= callTime) {
                userChatInfoVo.setChatCount(userChatInfoVo.getChatCount() - callTime);
                userChatInfoService.updateUserChatInfo(userChatInfoVo);
                log.info("扣减免费分钟数：{}", callTime);
                return true;
            } else {
                callTime -= userChatInfoVo.getChatCount();
                userChatInfoVo.setChatCount(0);
                userChatInfoService.updateUserChatInfo(userChatInfoVo);
                log.info("扣减免费分钟数不够：{}, 扣减：{}", callTime, userChatInfoVo.getChatCount());
            }
        }
        log.info("扣减余额");
        // 获取每分钟通话金额
        DefaultAmountConfigVo defaultAmountConfigVo = defaultAmountConfigService.queryDefaultAmountConfigByCode(DefaultAmountTypeEnum.CALL.getCode());
        BigDecimal payAmount = defaultAmountConfigVo.getAmount().multiply(BigDecimal.valueOf(callTime));
        // 扣减当前人余额
        UserBalanceInfoAddVo userBalanceInfoAddVo = new UserBalanceInfoAddVo();
        userBalanceInfoAddVo.setUserId(dbUser.getId());
        userBalanceInfoAddVo.setAmount(payAmount);
        userBalanceInfoService.reduceAmount(userBalanceInfoAddVo, null, TransactionType.CALL.getCode(), TransactionType.CALL.getValue());
        // 2024/10/27 释放账号
        try {
            aliyunDyplsService.unBindPhone(content.getPoolKey(), content.getSubId(), content.getSecretNo());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            // 这里可以解析消息体，根据文档解析具体格式
            System.out.println("Test SecretReport Message Success!");
        } catch (com.google.gson.JsonSyntaxException e) {
            log.info("error_json_format:" + message.getMessageBodyAsString(), e);
            return true;  // JSON格式错误则直接删除消息
        } catch (Throwable e) {
            return false;  // 业务异常，返回false以便重新推送消息
        }
        return true;  // 处理成功，删除消息
    }
}
